package com.cool.ce.client;

import com.alibaba.fastjson.JSONObject;
import com.cool.ce.exception.CeApiExceptionHandler;
import com.cool.common.model.request.FarecenterCeRequest;
import com.cool.common.utils.HttpClientBuilder;
import com.cool.orchestration.client.ThirdPartyApiHttpClient;
import jakarta.annotation.Resource;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.springframework.stereotype.Component;

import java.util.UUID;


@Component
public class CeApiClient implements ThirdPartyApiHttpClient<FarecenterCeRequest> {

    @Resource
    private CeApiExceptionHandler ceApiExceptionHandler;

    @Override
    public JSONObject execute(FarecenterCeRequest farecenterCeRequest) {
        HttpClientBuilder httpClientBuilder = new HttpClientBuilder()
                .baseUrl(farecenterCeRequest.getBaseUrl())
                .addQueryParam("appName", farecenterCeRequest.getAppName())
                .addQueryParam("interfaceName", farecenterCeRequest.getInterfaceName())
                .addQueryParam("version", farecenterCeRequest.getVersion())
                .addQueryParam("channel", farecenterCeRequest.getVersion())
                .addQueryParam("contentType", farecenterCeRequest.getContentType())
                .addQueryParam("channel", farecenterCeRequest.getChannel())
                .addQueryParam("signature", farecenterCeRequest.getSignature())
                .addQueryParam("timestamp", String.valueOf(System.currentTimeMillis()))
                .addQueryParam("requestId", UUID.randomUUID().toString().replace("-", ""))
                .jsonBody(farecenterCeRequest.getBusinessParam());
        try (Response post = httpClientBuilder.post() ) {
            ResponseBody responseBody = post.body();
            if (responseBody != null) {
                String string = responseBody.string();
                return JSONObject.parseObject(string);
            }
        } catch (Exception e) {
            throw ceApiExceptionHandler.handleException(e);
        }
        return null;
    }
}
